const fs = require('fs');
// const Web3 = require('web3');
const { Web3 } = require('web3');
const path = require('path');

// 读取 ABI 文件和合约字节码
const MarketplaceABI = require('./ABIs/Marketplace.json');
const UserListABI = require('./ABIs/UserList.json');


// 构建字节码文件的绝对路径
const Marketplace_bytecodecodePath = path.join(__dirname, 'ABIs', 'Marketplace_bytecode.txt');
const UserListBytecodePath = path.join(__dirname, 'ABIs', 'UserList_bytecode.txt');


const Marketplace_bytecodecodePathfs = fs.readFileSync(Marketplace_bytecodecodePath, 'utf8');
const UserListBytecodePathfs = fs.readFileSync(UserListBytecodePath, 'utf8');


// 创建一个 Web3 实例，并指定以太坊节点地址
// const web3 = new Web3('http://localhost:8545');
const web3 = new Web3('http://127.0.0.1:8545');

// 部署合约函数
async function deployContract(abi, bytecode) {
  const accounts = await web3.eth.getAccounts();
  const contract = new web3.eth.Contract(abi);
  const deploy = contract.deploy({ data: '0x' + bytecode }); // 注意添加 '0x' 前缀
  const gas = await deploy.estimateGas();
  const instance = await deploy.send({
    from: accounts[0],
    gas: gas,
  });
  return instance.options.address;
}

// 部署合约并写入地址到 JSON 文件
async function deployAndWriteAddress() {
  try {
    const UserListAddress = await deployContract(UserListABI, UserListBytecodePathfs);
    const materialListAddress = await deployContract(MarketplaceABI, Marketplace_bytecodecodePathfs);


    const addresses = {
      UserListAddr: UserListAddress,
      MaterialListAddr: materialListAddress,
    };

    fs.writeFileSync(path.join(__dirname, 'address.json'), JSON.stringify(addresses, null, 2));
    console.log('Addresses written to address.json');
  } catch (error) {
    console.error('Error deploying contracts:', error);
  }
}

// 执行部署函数
deployAndWriteAddress();
